﻿using CKS.Core.Framework;
using FreeSql;
using FreeSql.Internal.Model;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Enum;
using ZR.Model.Models.ProductionControl;


namespace CKS.PLC.Action
{
    public  abstract partial class PLCAction
    {
        /*
                    1 => "翅片_QXA",
                    2 => "盖板QXK",
                    3 => "底板QXM",
                    4 => "水嘴大焊环QXW",
                    5 => "定位柱小焊环QXZ",
                    6 => "焊丝QXX",
                    7 => "焊片QXY",
                    8 => "中板QXH",
                    9 => "接头QXN",
                    10 => "定位柱QXG",
         */
        /// <summary>
        /// 根据零件类型查询最新的零件批次
        /// </summary>
        /// <param name="PartType"></param>
        /// <returns></returns>
        public string GetPartBatchNo(int PartType)
        {
            var model = conn.Select<CksBatchofpart>().Where(a=>a.PartType == PartType)
                .OrderByDescending(a=>a.Id).First();
            if(model!=null && model.Status == 1 )
                return model.BatchNo;
            return string.Empty;
        }
        /// <summary>
        /// 更新子篮剩余零件数量
        /// </summary>
        /// <param name="bluecode"></param>
        /// <param name="stock"></param>
        public void UpdateBasketStock(string bluecode,int stock)
        {
            try
            {
                if (bluecode.IsEmpty() || bluecode.ToLower().StartsWith("error"))
                    return;
                var count = conn.Update<CksBasket>()
                    .Set(a => a.Stock, stock)
                    .Set(a => a.UpdateTime, DateTime.Now)
                    .Set(a => a.Status, 2)
                    .Where(a => a.BlueCode == bluecode)
                    .ExecuteAffrows();
                //if (count == 0)
                //{
                //    var PartType = GetPartType(bluecode);
                //    var basket = new CksBasket() { BlueCode = bluecode, CreatedTime = DateTime.Now, Type = PartType };
                //    basket.Stock = stock;
                //    basket.Status = 2;
                //    db.Insertable(basket).ExecuteCommand();
                //}
            }
            catch (Exception ex)
            {
                EventBus.AddError(ex,$"更新子篮{bluecode}异常");
            }
        }

        public bool CheckCodeIsError(string code)
        {
            if (code.IsEmpty() || code.ToLower().StartsWith("error"))
            {
                
                return true;
            }
            return false;
        }

        public void UpdateBasketStock(PartTypeEnum partType )
        {
           var baskets = conn.Select<CksBasket>()
                .Where(a => a.Type == (int)partType && a.Status == 2 && a.Stock > 0)
                .OrderByDescending(a => a.UpdateTime)
                .Take(2).ToList();
            var usageCount = conn.Select<CksPart>().Where(a => a.PartType == (int)partType).First().SingleUsageCount;
            if (baskets.Count == 0)
                return;
            if( baskets[0].Stock >= usageCount )
            {
                baskets[0].Stock = baskets[0].Stock - usageCount;
                baskets[0].UpdateTime = DateTime.Now;
                conn.Update<CksBasket>().SetSource(baskets[0])
                    .UpdateColumns(a=>new { a.Stock,a.UpdateTime }).ExecuteAffrows();
            }
            else if(baskets.Count ==1)
            {
                baskets[0].Stock =0;
                baskets[0].UpdateTime = DateTime.Now;
                conn.Update<CksBasket>().SetSource(baskets[0])
                    .UpdateColumns(a => new { a.Stock, a.UpdateTime }).ExecuteAffrows();
            }
            else if(baskets.Count == 2)//第一框扣减不足
            {
               var diffCount  = usageCount - baskets[0].Stock;
                baskets[0].Stock = 0;
                baskets[0].UpdateTime = DateTime.Now;

                baskets[1].Stock = baskets[1].Stock - diffCount;
                if (baskets[1].Stock < 0)
                    baskets[1].Stock = 0;
                baskets[1].UpdateTime = DateTime.Now;

                conn.Update<CksBasket>().SetSource(baskets)
                    .UpdateColumns(a => new { a.Stock, a.UpdateTime }).ExecuteAffrows();
            }


        }

        public void UpdateBasketStockWithConn(PartTypeEnum partType)
        {
            var baskets = conn.Select<CksBasket>()
                 .Where(a => a.Type == (int)partType && a.Status == 2 && a.Stock > 0)
                 .OrderByDescending(a => a.UpdateTime)
                 .Take(2).ToList();
            var usageCount = conn.Select<CksPart>().Where(a => a.PartType == (int)partType).First().SingleUsageCount;
            if (baskets.Count == 0)
                return;
            if (baskets[0].Stock >= usageCount)
            {
                baskets[0].Stock = baskets[0].Stock - usageCount;
                baskets[0].UpdateTime = DateTime.Now;
                conn.Update<CksBasket>().SetSource(baskets[0]).UpdateColumns(a => new { a.Stock, a.UpdateTime }).ExecuteAffrows();
            }
            else if (baskets.Count == 1)
            {
                baskets[0].Stock = 0;
                baskets[0].UpdateTime = DateTime.Now;
                conn.Update<CksBasket>().SetSource(baskets[0]).UpdateColumns(a => new { a.Stock, a.UpdateTime }).ExecuteAffrows();
            }
            else if (baskets.Count == 2)//第一框扣减不足
            {
                var diffCount = usageCount - baskets[0].Stock;
                baskets[0].Stock = 0;
                baskets[0].UpdateTime = DateTime.Now;

                baskets[1].Stock = baskets[1].Stock - diffCount;
                if (baskets[1].Stock < 0)
                    baskets[1].Stock = 0;
                baskets[1].UpdateTime = DateTime.Now;

                conn.Update<CksBasket>().SetSource(baskets).UpdateColumns(a => new { a.Stock, a.UpdateTime }).ExecuteAffrows();


            }


        }

        public object UpdateDynamicTableData(TableInfo fsqlTable, Dictionary<string, object> dict)
        {
            object obj = fsqlTable.CreateInstance(dict);
            conn.Update<object>().AsType(fsqlTable.Type)
                                .SetSource(obj).UpdateColumns(a => dict.Keys.ToArray()).ExecuteAffrows();
            return obj;
        }

        public  bool CatchAction(System.Action action,string logTitle = "保存数据库")
        {
            try
            {
                action();
                return true;
            }
            catch(Exception ex)
            {
                EventBus.AddLog($"{logTitle} 异常 {ex.Message}");
                return false;
            }
        }


        /// <summary>
        /// 获取字符串后缀
        /// </summary>
        /// <param name="content"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public string GetSuffix(string content, int len = 4)
        {
            if (content.IsNullOrEmpty())
                return "";
            if (content.Length < len)
                return "";
            return content.Substring(content.Length - len);
        }
    }
}
